package fragmentson;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import bean.MessageForSimple;
import fragmentson.backhandle.BackHandledFragment;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;

/**
 * 设备追踪
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class Trace extends BackHandledFragment {

	private View rootView;
	private TextureMapView mapView;
	private AMap aMap;
	//mode 0基础地图1卫星地图 road 0路况模式 1非路况模式
	private int mode=0,road=0;
	private GeocodeSearch geocoderSearch;
	private TextView tv_address;
	private Timer timer;
	MarkerOptions markerOption;
	private ArrayList<LatLng> tracks;
	private Polyline polyline;//线路
	private Marker markerCar = null;
	private PowerManager.WakeLock mWakeLock;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		rootView = getLayoutInflater(savedInstanceState).inflate(R.layout.fragment_trace, null);
		/*初始化地图和amap对象*/
		mapView = (TextureMapView) rootView.findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		if (aMap == null) {
			aMap = mapView.getMap();
		}
		tracks = new ArrayList<LatLng>();
		initView();
		initMapView();
		initData();
		return rootView;
	}

	private void initData(){
		ApiUtil.getApiService().getDevice(DemoApplication.getToken(),DemoApplication.getDeviceid()).enqueue(new Callback<MessageForSimple>() {
			@Override
			public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
				try {
					MessageForSimple entity = response.body();
					if(entity.getCode().equals("10008")){
						//如果想改变地图中心点
						aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.valueOf(entity.getData().getLat()), Double.valueOf(entity.getData().getLng())),16,0,0)));
						tracks.add(new LatLng(Double.parseDouble(entity.getData().getLat()),Double.parseDouble(entity.getData().getLng())));
						initMarker(DemoApplication.getmarker(entity.getData().getIcon()),entity.getData().getDevicename());
						((TextView) rootView.findViewById(R.id.tv_time)).setText(entity.getData().getReporttime());
						((TextView) rootView.findViewById(R.id.tv_gpstime)).setText(entity.getData().getReporttime());
						((TextView) rootView.findViewById(R.id.tv_devicename)).setText(entity.getData().getDevicename());
						((TextView) rootView.findViewById(R.id.tv_state)).setText(entity.getData().isonline()?getResources().getString(R.string.online):getResources().getString(R.string.up_pull_leave));
						((TextView) rootView.findViewById(R.id.tv_state)).setTextColor(entity.getData().isonline()?getResources().getColor(R.color.isline):getResources().getColor(R.color.textcolor2));
						((TextView) rootView.findViewById(R.id.tv_power)).setText(entity.getData().isonline()?entity.getData().getPower()+getResources().getString(R.string.unit2):"");
						((ImageView) rootView.findViewById(R.id.iv_power)).setImageResource(entity.getData().isonline()?DemoApplication.getPower(entity.getData().getPower()):R.mipmap.icon_unline);
						((TextView) rootView.findViewById(R.id.tv_speed)).setText(entity.getData().getSpeed()+getResources().getString(R.string.unit1));
						initGeocoder();
						getAddress(entity.getData().getLat(),entity.getData().getLng());
						timing();
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSimple> call, Throwable t) {
				Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
			}
		});
	}

	private void initData1(){
		ApiUtil.getApiService().getDevice(DemoApplication.getToken(),DemoApplication.getDeviceid()).enqueue(new Callback<MessageForSimple>() {
			@Override
			public void onResponse(Call<MessageForSimple> call, Response<MessageForSimple> response) {
				try {
					MessageForSimple entity = response.body();
					if(entity.getCode().equals("10008")){
						//如果想改变地图中心点

						LatLng marker1 = new LatLng(Double.valueOf(entity.getData().getLat()), Double.valueOf(entity.getData().getLng()));
						//设置中心点和缩放比例
						aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
						//aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.valueOf(entity.getData().getLat()), Double.valueOf(entity.getData().getLng())),16,0,0)));
						tracks.add(new LatLng(Double.parseDouble(entity.getData().getLat()),Double.parseDouble(entity.getData().getLng())));
						moverCar();
						((TextView) rootView.findViewById(R.id.tv_time)).setText(entity.getData().getGsmtime());
						((TextView) rootView.findViewById(R.id.tv_gpstime)).setText(entity.getData().getReporttime());
						((TextView) rootView.findViewById(R.id.tv_devicename)).setText(entity.getData().getDevicename());
						((TextView) rootView.findViewById(R.id.tv_state)).setText(entity.getData().isonline()?getResources().getString(R.string.online):getResources().getString(R.string.up_pull_leave));
						((TextView) rootView.findViewById(R.id.tv_power)).setText(entity.getData().getPower()+getResources().getString(R.string.unit2));
						((ImageView) rootView.findViewById(R.id.iv_power)).setImageResource(DemoApplication.getPower(entity.getData().getPower()));

						initGeocoder();
						getAddress(entity.getData().getLat(),entity.getData().getLng());
					}else{
						Toast.makeText(getActivity(),entity.getMsg(),Toast.LENGTH_LONG).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			@Override
			public void onFailure(Call<MessageForSimple> call, Throwable t) {
				Toast.makeText(getActivity(),getResources().getString(R.string.error),Toast.LENGTH_LONG).show();
			}
		});
	}

	private void initView() {
		// TODO Auto-generated method stub

		PowerManager pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MyTag");

		((TextView) rootView.findViewById(R.id.tv_title)).setText(R.string.trace_title);
		//rootView.findViewById(R.id.tv_next).setOnClickListener(listener);
		rootView.findViewById(R.id.iv_mapmode).setOnClickListener(listener);
		rootView.findViewById(R.id.ll_road).setOnClickListener(listener);
		rootView.findViewById(R.id.iv_plus).setOnClickListener(listener);
		rootView.findViewById(R.id.iv_reduce).setOnClickListener(listener);
		tv_address = ((TextView) rootView.findViewById(R.id.tv_address));
	}

	private void initMapView(){
		//隐藏缩放组件
		aMap.getUiSettings().setZoomControlsEnabled(false);
		//logo位置
		aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
		aMap.getUiSettings().setRotateGesturesEnabled(false);
		aMap.getUiSettings().setCompassEnabled(true);
		//加载定位maker
		//initMarkers();
		/*locationBlue();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				locationBlue();
			}
		}, 2000);*/
		//设备点位
	}

	private void initMarker(int marker,String name){

		View view = getActivity().getLayoutInflater().inflate(R.layout.map_custom_info_window, null);
		((TextView) view.findViewById(R.id.title)).setText(name);
		((ImageView) view.findViewById(R.id.marker)).setImageResource(marker);


		markerOption = new MarkerOptions()
				.icon(BitmapDescriptorFactory.fromView(view))
				.position(tracks.get(0))
				.draggable(true);

		aMap.clear();
		if(markerCar!=null){
			markerCar.destroy();
			markerCar =null;
		}
		if(polyline!=null){
			polyline=null;
		}
		//创建移动车辆
		markerCar = aMap.addMarker(markerOption);
		polyline = aMap.addPolyline(new PolylineOptions().add(tracks.get(0)).add(tracks.get(0)).width(10).color(Color.argb(255, 0, 193, 114)));
	}

	private void moverCar(){
		Animation animation = new TranslateAnimation(tracks.get(tracks.size()-1));
		animation.setDuration(1000);
		animation.setInterpolator(new LinearInterpolator());
		animation.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart() {
				// TODO Auto-generated method stub
			}
			@Override
			public void onAnimationEnd() {
				// TODO Auto-generated method stub

			}
		});
		markerCar.setAnimation(animation);
		markerCar.setPosition(tracks.get(tracks.size()-1));//移动车辆
		polyline.setPoints(tracks);
		//aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(tracks.get(i), aMap.getCameraPosition().zoom), 1000, null);
		markerCar.startAnimation();
	}

	public void getAddress(String latitude,String longitude){
		LatLonPoint latLonPoint = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
		geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
	}

	/**
	 * 初始化逆地理编码组件
	 */
	private void initGeocoder(){
		geocoderSearch = new GeocodeSearch(getActivity());
		geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
			@Override
			public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

				if (rCode == AMapException.CODE_AMAP_SUCCESS) {
					if (result != null && result.getRegeocodeAddress() != null
							&& result.getRegeocodeAddress().getFormatAddress() != null) {
						//Toast.makeText(getActivity(),result.getRegeocodeAddress().getFormatAddress(),Toast.LENGTH_LONG).show();
						tv_address.setText(result.getRegeocodeAddress().getFormatAddress());

					} else {
						Toast.makeText(getActivity(),"无数据",Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(getActivity(),rCode,Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

			}
		});
	}


	public void locationBlue(){
		MyLocationStyle myLocationStyle;
		myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
		myLocationStyle.strokeColor(Color.argb(0,0,0,0));
		myLocationStyle.radiusFillColor(Color.argb(0,0,0,0));//设置定位蓝点精度圆圈的填充颜色的方法。
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_arrows));// 设置小蓝点的图标
		myLocationStyle.anchor(0.5f,0.8f);
		myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//指定为一次并拉到中心
		//myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//指定为一次并拉到中心
		myLocationStyle.interval(10000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
		aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
		aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
	}

	public static Trace newInstance() {
		Trace fragment = new Trace();
		return fragment;
	}

	private View.OnClickListener listener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()){
				case R.id.iv_mapmode:
					if(mode==0) {
						((ImageView) v).setImageResource(R.mipmap.icon_right_map3);
						aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
						mode = 1;
					}else{
						((ImageView) v).setImageResource(R.mipmap.icon_right_map2);
						aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
						mode =0;
					}
					break;
				case R.id.ll_road:
					if(road==0) {
						((ImageView) rootView.findViewById(R.id.iv_road)).setImageResource(R.mipmap.icon_right_map5);
						aMap.setTrafficEnabled(true);
						road = 1;
					}else{
						((ImageView) rootView.findViewById(R.id.iv_road)).setImageResource(R.mipmap.icon_right_map4);
						aMap.setTrafficEnabled(false);
						road = 0;
					}
					break;
				case R.id.iv_plus:
					aMap.moveCamera(CameraUpdateFactory.zoomIn());
					break;
				case R.id.iv_reduce:
					aMap.moveCamera(CameraUpdateFactory.zoomOut());
					break;
				default:
					break;
			}
		}
	};

	@Override
	public boolean onBackPressed() {
		return false;
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onResume() {
		super.onResume();
		mapView.onResume();
		mWakeLock.acquire();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onPause() {
		super.onPause();
		mapView.onPause();
		mWakeLock.release();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();
		timer.cancel();
		mapView.onDestroy();
	}

	public void timing() {
		timer = new Timer(true);
		TimerTask task = new TimerTask() {
			public void run() {
				initData1();
			}
		};
		timer.schedule(task, 10000, 10000); // 延时1000ms后执行，1000ms执行一次
	}

}
